package com.gin.kotlin.no_gay_alliance.fragment.main.community

import android.content.Intent
import android.util.Log
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.LoginActivity
import com.gin.kotlin.no_gay_alliance.activity.LoginActivity.Companion.KEY_COOKIE
import com.gin.kotlin.no_gay_alliance.adapter.community.ForumSubGroupAdapter
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingFragment
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.database.entity.NgaAccount
import com.gin.kotlin.no_gay_alliance.databinding.FragmentMainCommunityFavorForumBinding
import com.gin.kotlin.no_gay_alliance.manager.AccountManager
import com.gin.kotlin.no_gay_alliance.model.ForumEntryModel
import com.gin.kotlin.no_gay_alliance.model.ForumSubGroupModel
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.FavorForumProvider
import com.gin.nga.cookie.NgaCookie
import com.gin.nga.enums.ForumType

/**
 * 收藏版面
 */
class MainFavorForumFragment : AbstractBindingFragment<FragmentMainCommunityFavorForumBinding>(), View.OnClickListener, ActivityResultCallback<ActivityResult> {
    private lateinit var adapter: ForumSubGroupAdapter
    private lateinit var launcher: ActivityResultLauncher<Intent>

    /**
     * 请求成功后赋值，表示当前页面的数据属于哪一个账号
     */
    private var currentUserId: Long = 0

    /**
     * onCreateView的后续操作 ，如通过  [FragmentActivity.addMenuProvider] 添加菜单
     */
    override fun onCreateView() {
        val b = this.b ?: return

        //初始化
        this.adapter = ForumSubGroupAdapter(requireContext(), handler!!, false)
        b.recyclerView.adapter = this.adapter
        b.tvWarning.setOnClickListener(this)
        this.launcher = registerLauncher(this)
        b.swipeRefreshLayout.setOnRefreshListener { request(true) }

        b.recyclerView.visibility = View.GONE
        request()
    }

    override fun onResume() {
        super.onResume()

        val b = this.b ?: return
        if (!b.swipeRefreshLayout.isRefreshing && currentUserId != App.INSTANCE.account.userId) {
            Log.d(TAG, "当前用户已切换, 重新请求收藏版面")
            request(true)
        }
    }

    /**
     * 发送请求
     */
    private fun request(ignoreCache: Boolean = false) {
        val b = this.b ?: return
        val userId = App.INSTANCE.account.userId


        //检查当前的登录状态

        if (userId == 0L) {
            //如果未登录，显示登录提示，点击事件为跳转登录
            b.tvWarning.text = getString(R.string.tv_please_login)
            b.tvWarning.visibility = View.VISIBLE
        } else {
            // 显示加载动画，执行查询请求，如果请求成功显示版面信息，请求失败展示报错信息，点击事件为重试请求
            b.tvWarning.visibility = View.GONE
            b.swipeRefreshLayout.isRefreshing = true

            // 执行请求
            FavorForumProvider.getInstance().enqueue(ignoreCache = ignoreCache, callback = object : RCallback<List<ForumEntryModel>, Nothing> {
                override fun onSuccess(data: List<ForumEntryModel>, ignoreCache: Boolean) {
                    currentUserId = userId
                    val list: MutableList<ForumSubGroupModel> = mutableListOf()
                    val map = data.groupBy { it.type }
                    map[ForumType.FORUM]?.let { ForumSubGroupModel(ForumType.FORUM.value, it.toMutableList()) }?.also { list.add(it) }
                    map[ForumType.COL]?.let { ForumSubGroupModel(ForumType.COL.value, it.toMutableList()) }?.also { list.add(it) }
                    adapter.replaceData(list)
                    ui {
                        b.recyclerView.visibility = View.VISIBLE
                        b.tvWarning.visibility = View.GONE
                        b.swipeRefreshLayout.isRefreshing = false
                    }
                }

                override fun onError(errorMessage: String) {
                    ui {
                        b.tvWarning.visibility = View.VISIBLE
                        b.recyclerView.visibility = View.GONE
                        b.swipeRefreshLayout.isRefreshing = false
                        b.tvWarning.text = errorMessage
                    }
                }
            })

        }
    }


    override fun onClick(v: View?) {
        // 警告信息的点击事件
        if (v == b?.tvWarning) {
            if (App.INSTANCE.account.userId > 0) {
                //重试请求
                request()
            } else {
                // 启动登陆活动
                this.launcher.launch(Intent(context, LoginActivity::class.java))
            }
        }
    }

    override fun onActivityResult(result: ActivityResult) {
        val cookie = result.data?.getStringExtra(KEY_COOKIE)
        val accountManager = AccountManager.getInstance()

        val account = NgaAccount(NgaCookie(cookie!!))
        accountManager.add(account)
        accountManager.setEnableLogin(account.userId)
        toast(getString(R.string.toast_message_account_logged, account.username))
        request(true)
    }
}